package win.smartown.aqst.demo.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.v7.widget.AppCompatEditText;
import android.util.AttributeSet;
import android.view.Gravity;

import win.smartown.aqst.demo.R;

/**
 * @author 雷小武
 * 创建时间：2018/11/7 14:41
 * 版权：成都智慧一生约科技有限公司
 * 类描述：
 */
public class RoundEditText extends AppCompatEditText {

    private int borderWidth;
    private int borderColor;
    private int borderColorFocus;

    private Paint paint;

    public RoundEditText(Context context) {
        super(context);
        init(null);
    }

    public RoundEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public RoundEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        if (attrs != null) {
            TypedArray typedArray = getResources().obtainAttributes(attrs, R.styleable.RoundEditText);
            borderWidth = typedArray.getDimensionPixelSize(R.styleable.RoundEditText_borderWidth, 1);
            borderColor = typedArray.getColor(R.styleable.RoundEditText_borderColor, Color.LTGRAY);
            borderColorFocus = typedArray.getColor(R.styleable.RoundEditText_borderColorFocus, Color.DKGRAY);
            typedArray.recycle();
        } else {
            borderWidth = 1;
            borderColor = Color.LTGRAY;
            borderColorFocus = Color.DKGRAY;
        }

        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStrokeWidth(borderWidth);
        paint.setStyle(Paint.Style.STROKE);
        setBackgroundResource(0);
        setGravity(Gravity.CENTER_VERTICAL);
        setSingleLine();
    }

    @Override
    public void draw(Canvas canvas) {
        if (isFocused()) {
            paint.setColor(borderColorFocus);
        } else {
            paint.setColor(borderColor);
        }
        int left = getScrollX() + borderWidth;
        int right = getScrollX() + getWidth() - borderWidth;
        int radius = getHeight() / 2 - borderWidth;
        canvas.drawRoundRect(new RectF(left, borderWidth, right, getHeight() - borderWidth), radius, radius, paint);
        super.draw(canvas);
    }

}